package com.core.admin.action;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.annotation.RequiredStringValidator;
import com.annotation.Validations;
import com.annotation.validator.ExecutionValidator;
import com.annotation.validator.WebValidateErrors;
import com.common.web.MemberUtils;
import com.core.admin.action.service.WebMessage;
import com.core.entity.User;
import com.core.manager.UserMng;
import com.core.manager.impl.UserMngImpl;
import com.core.manager.impl.UserMngImpl.UserPwdNotEqualException;
import com.core.manager.impl.UserMngImpl.UserRepeatingDataException;
import com.core.manager.impl.UserMngImpl.UsernameNotFoundException;

@Controller
public class UserAct {
	@Resource(type = ExecutionValidator.class)
	ExecutionValidator exec;
	@Resource(type = UserMngImpl.class)
	UserMng userMng;

	@RequestMapping("/login.do")
	public String login() {
		return "login";
	}

	@Validations(requiredStrings = {
			@RequiredStringValidator(fieldName = "userName", message = "用户名不能为空"),
			@RequiredStringValidator(fieldName = "pwd", message = "密码不能为空") })
	@RequestMapping("/validateLogin.do")
	public String validateLogin(String userName, String pwd, ModelMap model) {
		exec.validate(this.getClass(), "validateLogin");
		if (WebValidateErrors.hasErrors()) {
			WebValidateErrors.toModel(model);
			return login();
		}
		try {
			User user = userMng.login(userName, pwd);
			MemberUtils.setLoginMember(user);
			return "redirect:main.do";
		} catch (UsernameNotFoundException e) {
			return WebMessage.create().addErrorMessage(e.getMessage())
					.showPage(model);
		} catch (UserRepeatingDataException e) {
			return WebMessage.create().addErrorMessage(e.getMessage())
					.showPage(model);
		} catch (UserPwdNotEqualException e) {
			return WebMessage.create().addErrorMessage(e.getMessage())
					.showPage(model);
		}
	}

	@RequestMapping("/message.do")
	public String message(ModelMap model) {
		return WebMessage.create().addMSGStr("操作成功").showPage(model);
	}

}
